package com.softstao.guoyu.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseFragment;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.me.ApplyList;
import com.softstao.guoyu.model.me.ApplyListIndex;
import com.softstao.guoyu.mvp.interactor.me.BalanceInteractor;
import com.softstao.guoyu.mvp.presenter.me.BalancePresenter;
import com.softstao.guoyu.mvp.viewer.me.ApplyListViewer;
import com.softstao.guoyu.ui.activity.me.ChooseAgentActivity;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewHolder;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.EmptyLayout;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by vaikus on 2017/6/15.
 */

public class ApplyListFragment extends BaseFragment implements ApplyListViewer, TextWatcher {

    @AIPresenter(presenter = BalancePresenter.class, interactor = BalanceInteractor.class)
    BalancePresenter presenter;

    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.scrollView)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.search_v)
    EditText searchView;
    private RecycleViewBaseAdapter<ApplyList> adapter;
    private List<ApplyList> datas = new ArrayList<>();
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String keyword = "";

    @Override
    public int _ContentView() {
        return R.layout.fragment_apply_list;
    }

    @Override
    public void initView() {
        scrollView.setOnScrollChangedListener(this);
        setPtrFrameLayoutEnable();
        search();

        adapter = new RecycleViewBaseAdapter<ApplyList>(datas, R.layout.layout_apply_item) {
            @Override
            public void convert(RecycleViewHolder holder, ApplyList applyList) {
                RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                holder.itemView.setLayoutParams(layoutParams);
                holder.setText(R.id.name, applyList.getName())
                        .setText(R.id.level, applyList.getLevel())
                        .setText(R.id.time, format.format(new Date(applyList.getDate())));
                switch (applyList.getInorout()) {
                    case 0:
                        holder.setText(R.id.money, "+" + LZUtils.priceFormat(applyList.getMoney()) + "元");
                        break;
                    case 1:
                        holder.setText(R.id.money, "-" + LZUtils.priceFormat(applyList.getMoney()) + "元");
                        break;
                }
            }
        };
        listView.setAdapter(adapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(mContext));
    }

    private void search() {
        searchView.setHint("代理名称");
        searchView.addTextChangedListener(this);
        searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchView.setInputType(EditorInfo.TYPE_CLASS_TEXT);
        searchView.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                try {
                    keyword = URLEncoder.encode(searchView.getText().toString(), "utf-8");
                    currentPage = 1;
                    findApplyList();
                    InputMethodManager mInputMethodManager = (InputMethodManager) mContext.getSystemService(INPUT_METHOD_SERVICE);
                    mInputMethodManager.hideSoftInputFromWindow(((Activity)mContext).getCurrentFocus().getWindowToken(), 0);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return false;
            }
            return true;
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        findApplyList();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        findApplyList();
    }

    @Override
    public void onLoad() {
        super.onLoad();
        loading.setVisibility(View.VISIBLE);
        findApplyList();
    }

    @Override
    public void findApplyList() {
        presenter.getApplyList(currentPage, SharePreferenceManager.getInstance().getAgentId(), keyword);
    }

    @Override
    public void getApplyList(ApplyListIndex applyListIndex) {
        loading.setVisibility(View.GONE);
        if (applyListIndex != null) {
            if (applyListIndex.getRecordList() != null && applyListIndex.getRecordList().size() != 0) {
                emptyLayout.setVisibility(View.GONE);
                more.setVisibility(View.GONE);
                if (currentPage == 1) {
                    datas.clear();
                }
                datas.addAll(applyListIndex.getRecordList());
                adapter.notifyDataSetChanged();
            } else {
                if (currentPage == 1) {
                    emptyLayout.setVisibility(View.VISIBLE);
                } else {
                    more.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @OnClick(R.id.submit_btn)
    public void onViewClicked() {
        startActivity(new Intent(mContext, ChooseAgentActivity.class));
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (searchView.getText().toString().equals("")){
            keyword = "";
            currentPage = 1;
            findApplyList();
        }
    }
}
